package com.bionic.banking.servlet;

import com.bionic.banking.auth.manager.Config;
import com.bionic.banking.auth.manager.Message;
import com.bionic.banking.commands.CommandCreateCustomer;
import com.bionic.banking.commands.ControllerHelper;
import com.bionic.banking.commands.ICommand;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet(name = "Controller", urlPatterns = {"/Controller"})
public class Controller extends HttpServlet {

    ControllerHelper controllerHelper = ControllerHelper.getInstance();

    public Controller() {
        super();
    }

    protected void processRequest(HttpServletRequest request,
            HttpServletResponse response) throws ServletException {
        String page = null;
        try {
            ICommand command = controllerHelper.getCommand(request);
            page = command.execute(request, response);
            HttpSession session = request.getSession(false);
            if (session != null && command instanceof CommandCreateCustomer) {
                session.setAttribute("content", page);
            }
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(page);
            dispatcher.forward(request, response);

        } catch (ServletException e) {
            request.setAttribute("messageError",
                    Message.getInstance().getProperty(Message.SERVLET_EXCEPTION));
            page = Config.getInstance().getProperty(Config.ERROR);
        } catch (IOException ex) {
            request.setAttribute("messageError",
                    Message.getInstance().getProperty(Message.IO_EXCEPTION));
            page = Config.getInstance().getProperty(Config.ERROR);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Application Controller servler";
    }
}
